package cn.com.bsoft.cloud.service;

import cn.com.bsoft.cloud.dao.cloud.CfmessDao;
import cn.com.bsoft.cloud.dao.cloud.PrescriptionDetailDao;
import cn.com.bsoft.cloud.entity.cloud.*;
import cn.com.bsoft.cloud.entity.param.PrescriptionDetailDTO;
import cn.com.bsoft.cloud.entity.param.PrescriptionDetailParam;
import cn.com.bsoft.cloud.entity.param.dto.DoctorInfo;
import cn.com.bsoft.cloud.entity.param.dto.PatientInfo;
import cn.com.bsoft.cloud.entity.param.dto.PrescriptionMedicines;
import cn.com.bsoft.cloud.utils.ESignUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.jsoup.helper.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Transactional(value="txManagerCloud")
public class HisInterfaceImpl implements HisInterface{

    @Autowired
    private CfmessDao cfmessDao;
    @Autowired
    private PrescriptionDetailDao prescriptionDetailDao;


    @Override
    public boolean updateCaSgin(String prescriptionCode , String caSign) {
        return cfmessDao.updateCaSgin(prescriptionCode ,  caSign);
    }

    @Override
    public boolean hisSendMessage(Cfmesses cfmesses, String yyid,String prescriptionCode,String telphone) {
        return cfmessDao.addAppointMess(cfmesses,yyid,prescriptionCode,telphone);
    }

    @Override
    public List<PrescriptionDetailDTO> queryPrescriptionDetail(PrescriptionDetailParam prescriptionDetail) {
        //1 查处方
        String sqlcf="select prescriptionCode as recordId,'' as visitRecordId,'fz' as prescriptionType,\n" +
                "'5 'pharmacyId,'' provinceNum,'' provinceName,'' cityNum,'' cityName,'' countyNum,'' countyName,\n" +
                "'' townNum,'' townName,null as  address, now() as sendDate,\n" +
                " patientName as receiverName, '' as receiverPhone,'zc' as  status " +
                ",now() as createDate, null as lastModifyDate ,doctorCode" +
                " from t_prescription_drug_list ";
        List<Map> list = prescriptionDetailDao.query(sqlcf);
        List<PrescriptionDetailDTO> prescriptionDetailDTOList = new ArrayList<PrescriptionDetailDTO>();
        System.out.println("xxxxx=="+list.size());
        for(Map item: list){
            PrescriptionDetailDTO prescriptionDetailDTO = new PrescriptionDetailDTO();
            String prescriptionCode = nullToStr(item.get("recordId"));
            String  doctorCode= nullToStr(item.get("doctorCode"));
            prescriptionDetailDTO.setRecordId(prescriptionCode);
            prescriptionDetailDTO.setVisitRecordId(nullToStr(item.get("visitRecordId")));
            prescriptionDetailDTO.setPrescriptionType(nullToStr(item.get("prescriptionType")));
            prescriptionDetailDTO.setPharmacyId(nullToStr(item.get("pharmacyId")));
            prescriptionDetailDTO.setProvinceNum(nullToStr(item.get("provinceNum")));
            prescriptionDetailDTO.setProvinceName(nullToStr(item.get("provinceName")));
            prescriptionDetailDTO.setCityNum(nullToStr(item.get("cityNum")));
            prescriptionDetailDTO.setCityName(nullToStr(item.get("cityName")));
            prescriptionDetailDTO.setCountyNum(nullToStr(item.get("countyNum")));
            prescriptionDetailDTO.setCountyName(nullToStr(item.get("countyName")));
            prescriptionDetailDTO.setTownNum(nullToStr(item.get("townNum")));
            prescriptionDetailDTO.setTownName(nullToStr(item.get("townName")));
            prescriptionDetailDTO.setAddress(nullToStr(item.get("address")));
            prescriptionDetailDTO.setReceiverName(nullToStr(item.get("receiverName")));
            prescriptionDetailDTO.setReceiverPhone(nullToStr(item.get("receiverPhone")));
            prescriptionDetailDTO.setStatus(nullToStr(item.get("status")));
         ;
           //2 查处方明细
            String mxSql = "SELECT frequencyCode as frequency,frequencyName ," +
                    "'' as drugUseWay, '' as drugUseWayName,\n" +
                    " doseUnitName as useUnit, ' ' AS packagingNumber,  ' ' as minPackingUnit,'' as  medicinePrices, ' ' AS drugsUp \n" +
                    " from  t_prescription_drug_detail where prescriptionCode='"+prescriptionCode+"'order by createtime desc limit 1 ";
            System.out.println("mxSql=="+mxSql);
            List<Map> mxList = prescriptionDetailDao.query(mxSql);
//            System.out.println("mxList="+mxList.toString());
            List<PrescriptionMedicines> prescriptionMedicinesList = new ArrayList<PrescriptionMedicines>();
            if(mxList!=null&&mxList.size()>0){
                for(Map mx : mxList){
                    PrescriptionMedicines pres=new PrescriptionMedicines();
                    pres.setFrequency(nullToStr(mx.get("frequency")));
                    pres.setFrequencyName(nullToStr(mx.get("frequencyName")));
                    pres.setUseUnit(nullToStr(mx.get("useUnit")));
                    prescriptionMedicinesList.add(pres);
                    System.out.println("pres=="+pres.toString());
                }
            }
//            System.out.println("prescriptionMedicinesList="+prescriptionMedicinesList.toString());
            prescriptionDetailDTO.setPrescriptionMedicinesList(prescriptionMedicinesList);
            //3 查doctor
            String  doctorSql = "select  workNumber as doctorCode, doctorName,'' doctorRank," +
                    "departmentCode,departmentName,medicalInstitutionCode as hospitalCode," +
                    "medicalInstitutionName as hospitalName from t_doctor_information  where workNumber='"+doctorCode+"'";
            List<Map> doctorMapList = prescriptionDetailDao.query(doctorSql);
            DoctorInfo doctorInfo=new DoctorInfo();
            if(doctorMapList!=null&&doctorMapList.size()>0){
                Map m = doctorMapList.get(0);
                     doctorInfo.setDoctorCode(nullToStr(m.get("doctorInfo")));
                    doctorInfo.setDoctorName(nullToStr(m.get("doctorName")));
                    doctorInfo.setDoctorRank(nullToStr(m.get("doctorRank")));
                    doctorInfo.setDepartmentCode(nullToStr(m.get("departmentCode")));
                    doctorInfo.setDepartmentName(nullToStr(m.get("departmentName")));
                    doctorInfo.setHospitalCode(nullToStr(m.get("hospitalCode")));
                    doctorInfo.setHospitalName(nullToStr(m.get("hospitalName")));
              }
            prescriptionDetailDTO.setDoctorInfo(doctorInfo);
            PatientInfo patientInfo  = new PatientInfo();
            patientInfo.setPatientName(nullToStr(item.get("receiverName")));
            prescriptionDetailDTO.setPatientInfo(patientInfo);
            prescriptionDetailDTOList.add(prescriptionDetailDTO);
        }
//         System.out.println("prescriptionDetailDTOList="+prescriptionDetailDTOList.toString());
        if(prescriptionDetailDTOList!=null&&prescriptionDetailDTOList.size()>0){
            for (PrescriptionDetailDTO prescriptionDetailDTO : prescriptionDetailDTOList) {
                Double tempToatl = 0d;
                for (PrescriptionMedicines prescriptionMedicines : prescriptionDetailDTO.getPrescriptionMedicinesList()) {
                    if (StringUtil.isBlank(prescriptionMedicines.getDetailId()))
                        continue;
                    double num = Double.valueOf(prescriptionMedicines.getNumber());
                    tempToatl += prescriptionMedicines.getMedicinePrices() * num;
                }
                BigDecimal bg = new BigDecimal(tempToatl);
                double total = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                prescriptionDetailDTO.setTotalPrice(total);
                //添加处方签
                if ("1".equals(prescriptionDetailDTO.getDoctorSign()) && "1".equals(prescriptionDetailDTO.getPharmacistSign())) {
                    String url = "https://bohemia.bshcn.com.cn/esign/prescription/display?domain=mzhongxin.doctor&hospitalCode=" + prescriptionDetailDTO.getDoctorInfo().getHospitalCode() + "&prescriptionCode=" + prescriptionDetailDTO.getRecordId() + "&outputType=image";
                    prescriptionDetailDTO.setPrescriptionNotesUrl(url);
                }
                if ("0".equals(prescriptionDetailDTO.getReceiveType())) {
                    if (prescriptionDetailDTO.getAmount() != null) {
                        prescriptionDetailDTO.setSendStatus("70");
                    } else if ("0".equals(prescriptionDetailDTO.getOfflineCheckStatus())) {
                        prescriptionDetailDTO.setSendStatus("60");
                    } else if ("2".equals(prescriptionDetailDTO.getOfflineCheckStatus())) {
                        prescriptionDetailDTO.setSendStatus("50");
                    }
                }
                if ("1".equals(prescriptionDetailDTO.getReceiveType())) {
                    if ("0".equals(prescriptionDetailDTO.getOfflineCheckStatus())) {
                        prescriptionDetailDTO.setSendStatus("10");
                    } else if ("1".equals(prescriptionDetailDTO.getOfflineCheckStatus())) {
                        prescriptionDetailDTO.setSendStatus("20");
                    } else if ("2".equals(prescriptionDetailDTO.getOfflineCheckStatus())) {
                        prescriptionDetailDTO.setSendStatus("30");
                    } else if ("3".equals(prescriptionDetailDTO.getOfflineCheckStatus())) {
                        prescriptionDetailDTO.setSendStatus("40");
                    } else if (prescriptionDetailDTO.getOfflineCheckStatus() == null) {
                        prescriptionDetailDTO.setSendStatus("00");
                    }
                }
                JSONObject jsonObject =  updatePrescriptionDetailDTOSign(prescriptionDetailDTO,1,"mzhongxin.doctor");
                if(jsonObject.get("code").equals("1")){
                    String url = jsonObject.get("url").toString();
                    prescriptionDetailDTO.setPrescriptionNotesUrl(url);
                }
            }
        }
         return prescriptionDetailDTOList;
    }



    @Override
    public boolean yyidIsExists(String yyid) {
        int i= cfmessDao.yyidIsExists(yyid);
        if(i<=0){
            return true;//不存在
        }else{
            return false;//存在
        }
    }

    @Override
    public boolean insertAppointInformation(Appoint appoint) {
        return cfmessDao.insertAppointInformation(appoint);
    }

    @Override
    public boolean cfmxbatchInsert(List<Cfmess> cfmess, String cfid) {
        return cfmessDao.cfmxbatchInsert(cfmess,cfid);
    }

    @Override
    public boolean updatePayStaus(UpdatePayStatus updatePayStatus) {
        List<String> list = updatePayStatus.getPrescriptionCode();
//        String codeStr = StringUtils.join( list.toArray(),",");
        StringBuffer sb = new StringBuffer();
            for (int i=0;i<list.size();i++) {
                if(i==0){
                    sb.append("'").append(list.get(i)).append("'");
                }else{
                    sb.append(",").append("'").append(list.get(i)).append("'");
                }
            }
        int i = cfmessDao.updatePayStaus(updatePayStatus,sb.toString());
        if(i>0){
            return true;
        }else{
            return false;
        }
    }

    @Override
    public int queryDeliveryStatus(String hospitalCode,List prescriptionCode) {
        StringBuffer sb = new StringBuffer();
        for (int i=0;i<prescriptionCode.size();i++) {
            if(i==0){
                sb.append("'").append(prescriptionCode.get(i)).append("'");
            }else{
                sb.append(",").append("'").append(prescriptionCode.get(i)).append("'");
            }
        }
        return cfmessDao.queryDeliveryStatus(hospitalCode,sb.toString());
    }

    @Override
    public boolean invalidPrescription(String hospitalCode,List prescriptionCode) {
        StringBuffer sb = new StringBuffer();
        for (int i=0;i<prescriptionCode.size();i++) {
            if(i==0){
                sb.append("'").append(prescriptionCode.get(i)).append("'");
            }else{
                sb.append(",").append("'").append(prescriptionCode.get(i)).append("'");
            }
        }
        return cfmessDao.invalidPrescription(hospitalCode,sb.toString());
    }

    @Override
    public int prescriptionIsExists(String hospitalCode, List prescriptionCode) {
        StringBuffer sb = new StringBuffer();
        for (int i=0;i<prescriptionCode.size();i++) {
            if(i==0){
                sb.append("'").append(prescriptionCode.get(i)).append("'");
            }else{
                sb.append(",").append("'").append(prescriptionCode.get(i)).append("'");
            }
        }
        return cfmessDao.prescriptionIsExists(hospitalCode,sb.toString());
    }

    @Override
    public int prescriptionIsPayed(String hospitalCode, List prescriptionCode) {
        StringBuffer sb = new StringBuffer();
        for (int i=0;i<prescriptionCode.size();i++) {
            if(i==0){
                sb.append("'").append(prescriptionCode.get(i)).append("'");
            }else{
                sb.append(",").append("'").append(prescriptionCode.get(i)).append("'");
            }
        }
        return cfmessDao.prescriptionIsPayed(hospitalCode,sb.toString());
    }

    @Override
    public boolean yyidsfcz(String yyid) {
        int i= cfmessDao.yyidsfcz(yyid);
        if(i<=0){
            return true;//不存在
        }else{
            return false;//存在
        }
    }

    @Override
    public List<master> queryCompanyParam(UpdatePayStatus updatePayStatus) {
        List<String> list = updatePayStatus.getPrescriptionCode();
        StringBuffer sb = new StringBuffer();
        for (int i=0;i<list.size();i++) {
            if(i==0){
                sb.append("'").append(list.get(i)).append("'");
            }else{
                sb.append(",").append("'").append(list.get(i)).append("'");
            }
        }
        return cfmessDao.queryCompanyParam(updatePayStatus,sb.toString());
    }

    @Override
    public String queryCompanyCode(UpdatePayStatus updatePayStatus) {
        List<String> list = updatePayStatus.getPrescriptionCode();
        StringBuffer sb = new StringBuffer();
        for (int i=0;i<list.size();i++) {
            if(i==0){
                sb.append("'").append(list.get(i)).append("'");
            }else{
                sb.append(",").append("'").append(list.get(i)).append("'");
            }
        }
        return cfmessDao.queryCompanyCode(updatePayStatus,sb.toString());
    }

    @Override
    public Map queryAppIdAndToken(String companyCode) {
        return cfmessDao.queryAppIdAndToken(companyCode);
    }

    @Override
    public int onePrescriptionIsExists(String hospitalCode, String prescriptionCode) {
        return cfmessDao.onePrescriptionIsExists(hospitalCode,prescriptionCode);
    }

    @Override
    public int prescriptionIsDelete(String hospitalCode, List prescriptionCode) {
        StringBuffer sb = new StringBuffer();
        for (int i=0;i<prescriptionCode.size();i++) {
            if(i==0){
                sb.append("'").append(prescriptionCode.get(i)).append("'");
            }else{
                sb.append(",").append("'").append(prescriptionCode.get(i)).append("'");
            }
        }
        return cfmessDao.prescriptionIsDelete(hospitalCode,sb.toString());
    }

    @Override
    public int prescriptionIsSend(String hospitalCode, List prescriptionCode) {
        StringBuffer sb = new StringBuffer();
        for (int i=0;i<prescriptionCode.size();i++) {
            if(i==0){
                sb.append("'").append(prescriptionCode.get(i)).append("'");
            }else{
                sb.append(",").append("'").append(prescriptionCode.get(i)).append("'");
            }
        }
        return cfmessDao.prescriptionIsSend(hospitalCode,sb.toString());
    }

    @Override
    public int prescriptionIsArrived(String hisPrescriptionCode,String hospitalCode) {
        return cfmessDao.prescriptionIsArrived(hisPrescriptionCode,hospitalCode);
    }

    @Override
    public prescriptionArriveResult prescriptionArrived(String hisPrescriptionCode,String hospitalCode) {
        return cfmessDao.prescriptionArrived(hisPrescriptionCode,hospitalCode);
    }

    @Override
    public boolean sendDrugs(String hospitalCode, List prescriptionCode) {
        StringBuffer sb = new StringBuffer();
        for (int i=0;i<prescriptionCode.size();i++) {
            if(i==0){
                sb.append("'").append(prescriptionCode.get(i)).append("'");
            }else{
                sb.append(",").append("'").append(prescriptionCode.get(i)).append("'");
            }
        }
        return cfmessDao.sendDrugs(hospitalCode,sb.toString());
    }
  public String nullToStr(Object o){
        return o==null?"":o.toString();
  }

    private JSONObject updatePrescriptionDetailDTOSign(PrescriptionDetailDTO prescriptionDetail,Integer signType,String flag) {
        prescriptionDetail.getPatientInfo().setPatientId("310112198812190912");
        JSONObject rsp = new JSONObject();
        //发送处方信息，  待测试，json是否能用  //TODO
        try {
            String jsonString = JSON.toJSONString(prescriptionDetail);
            //组装处方信息
            JSONArray array = new JSONArray();
            JSONObject obj = new JSONObject();
            obj.put("domain", flag);
            obj.put("hospitalCode", "42504704X00");
            obj.put("hospitalName", "闵行区中心医院");
//        obj.put("patientType", patientRegister.get.());
            obj.put("prescriptionCode", prescriptionDetail.getRecordId());
            obj.put("patientName", prescriptionDetail.getPatientInfo().getPatientName());

            obj.put("patientGender", ESignUtil.getIdentifyNoInfo(prescriptionDetail.getPatientInfo().getPatientId()).get("sex").toString());

            obj.put("patientAge", ESignUtil.getIdentifyNoInfo(prescriptionDetail.getPatientInfo().getPatientId()).get("age").toString() + "岁");
            obj.put("patientIdNo", prescriptionDetail.getPatientInfo().getPatientId());
            obj.put("patientId", prescriptionDetail.getPatientInfo().getPatientId());
            obj.put("patientMobile", "18856781223");
            obj.put("department", prescriptionDetail.getDoctorInfo().getDepartmentName());
            obj.put("clinicalDiagnosis", "扁桃体结核");
            List<PrescriptionMedicines> prescriptionMedicinesList = prescriptionDetail.getPrescriptionMedicinesList();
            for (PrescriptionMedicines prescriptionMedicines : prescriptionMedicinesList) {
                JSONObject obj1 = new JSONObject();

                obj1.put("itemCode", prescriptionMedicines.getStandardCode() == null ? "" : prescriptionMedicines.getStandardCode());
                obj1.put("itemName", prescriptionMedicines.getCommonTitle() == null ? "" : prescriptionMedicines.getCommonTitle());
                obj1.put("spec", prescriptionMedicines.getMedicineSpecifications() == null ? "" : prescriptionMedicines.getMedicineSpecifications());
                obj1.put("amount", prescriptionMedicines.getNumber() == null ? "" : prescriptionMedicines.getNumber());
                obj1.put("amountUnit", prescriptionMedicines.getUseUnit() == null ? "" : prescriptionMedicines.getUseUnit());//发药单位	 private String useUnit;//用药单位
                obj1.put("usageAmount", prescriptionMedicines.getDosage());
                obj1.put("usageUnit", prescriptionMedicines.getUnitDose());
                obj1.put("usageRoute", prescriptionMedicines.getDosage() == null ? "" : prescriptionMedicines.getDosage());//
                //           private String frequency;//用药频次
                //            private String frequencyName;//用药频次中文
                obj1.put("frep", prescriptionMedicines.getFrequency() == null ? "" : prescriptionMedicines.getFrequency());//
                obj1.put("usageTime", null);
                obj1.put("usageTimeUnit", null);
                array.add(obj1);
            }
            obj.put("items", array);

            JSONObject jsonObject = ESignUtil.prescriptionSubmit(obj);
            JSONObject jsonObjectSignReq = new JSONObject();
            //处方笺签名
            jsonObjectSignReq.put("hospitalCode", "42504704X00");
            jsonObjectSignReq.put("prescriptionCode", prescriptionDetail.getRecordId());
            //这里从哪里取，还是写死，目前是写死的
            jsonObjectSignReq.put("domain", flag);
            jsonObjectSignReq.put("loginName", "310112199303185686");//传医生身份证号
            jsonObjectSignReq.put("signType", signType);//医生签名
            JSONObject prescriptionSign = ESignUtil.prescriptionSign(jsonObjectSignReq);
            if (prescriptionSign.containsKey("url")) {
                if (!prescriptionSign.get("url").toString().trim().equals("")) {
                    //更新处方医生签名状态
                    if (signType == 1) {
                        prescriptionDetail.setDoctorSign("1");
                    }
                    if (signType == 2) {
                        prescriptionDetail.setPharmacistCheck("1");
                    }
                    updatePrescriptionDetailSignStatus(prescriptionDetail);
                }
                rsp.put("code", "1");
                rsp.put("url", prescriptionSign.get("url"));
                return rsp;
            }
        } catch (Exception e) {
            e.printStackTrace();
            rsp.put("code", "0");
            rsp.put("msg", "签章错误：" + e.getMessage());
        }
        return rsp;
    }

    private void updatePrescriptionDetailSignStatus(PrescriptionDetailDTO prescriptionDetail) {
        String sql = "update t_prescription_drug_list set doctorSign=1 where prescriptionCode='"+prescriptionDetail.getRecordId()+"'";
        prescriptionDetailDao.query(sql);
    }
}
